package start.demo01.cmd;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Main {

    public static void main(String[] args) throws IOException, InterruptedException {
        String command="netstat";
//        String command="ipconfig";
        ProcessBuilder processBuilder = new ProcessBuilder().command(command,"-abn");
//        Map<String, String> environment = processBuilder.environment();
//        Iterator<Map.Entry<String, String>> iterator = environment.entrySet().iterator();
//        while(iterator.hasNext()){
//            Map.Entry<String, String> next = iterator.next();
//            System.out.println(String.format("%-10s",next.getKey())+next.getValue());
//        }
        processBuilder.redirectErrorStream(true);
        Process p = processBuilder.inheritIO().start();
        System.out.println("已执行");
        InputStream is = p.getInputStream();
        BufferedReader bs = new BufferedReader(new InputStreamReader(is,"GBK"));
        p.waitFor();
        System.out.println("waitfor");
        if (p.exitValue() != 0) {
            //说明命令执行失败
            //可以进入到错误处理步骤中
            System.out.println("已失败");
        }
        String line;
        int i=0;
        while ((line = bs.readLine()) != null) {
            i++;
            System.out.println(line);
            if(i==2) {
                is.close();
                bs.close();
                p.destroy();
            }
//            resultLog += line;
        }
    }
}
